<template>
  <div class="add-wrapper">
    <el-page-header @back="goBack" :content="isAdd ? '创建订单' : '编辑订单'">
    </el-page-header>
    <div class="form-wrapper">
      <div class="top-form">
        <div class="descLabel">基本信息</div>
        <!-- @keyup.enter.native="dataFormSubmitHandle()" -->
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          @submit.native.prevent
          label-width="120px"
        >
          <el-form-item v-if="!isAdd" prop="order_serial" label="订单编号">
            <el-input v-model="dataForm.order_serial" disabled></el-input>
          </el-form-item>
          <el-form-item prop="name" label="订单名称">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <el-form-item prop="sale_date" label="销售日期">
            <el-date-picker
              v-model="dataForm.sale_date"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="customer_name" label="客户名称">
            <el-input v-model="dataForm.customer_name"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="联系方式">
            <el-input v-model="dataForm.phone"></el-input>
          </el-form-item>
          <el-form-item prop="customer_manager" label="客户经理">
            <el-input v-model="dataForm.customer_manager"></el-input>
          </el-form-item>
          <el-form-item prop="pay_type" label="结算方式">
            <ren-select
              v-model="dataForm.pay_type"
              dict-type="pay_type"
              placeholder="请选择"
            ></ren-select>
          </el-form-item>
          <el-form-item label="交货地址">
            <div class="disCenterBetween" style="position: relative">
              <el-select
                placeholder="选择省份"
                @change="provinceChange"
                v-model="province"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item.code"
                  :label="item.name"
                  :value="{ value: item.code, label: item.name }"
                ></el-option>
              </el-select>
              <el-select
                placeholder="选择市"
                style="margin-left: 12px"
                @change="cityChange"
                v-model="city"
              >
                <el-option
                  v-for="item in cities"
                  :key="item.code"
                  :label="item.name"
                  :value="{ value: item.code, label: item.name }"
                ></el-option>
              </el-select>
              <el-select
                placeholder="选择区"
                style="margin-left: 12px"
                v-model="area"
              >
                <el-option
                  v-for="item in areas"
                  :key="item.code"
                  :label="item.name"
                  :value="{ value: item.code, label: item.name }"
                ></el-option>
              </el-select>
              <div style="position: absolute; right: -31vw">
                <el-input
                  v-model="dataForm.address"
                  placeholder="详细地址"
                  style="width: 30vw"
                ></el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="remarks" label="备注">
            <el-input
              placeholder="请输入"
              type="textarea"
              :rows="3"
              v-model="dataForm.remarks"
            >
            </el-input>
          </el-form-item>

          <el-form-item label="产品明细">
            <el-button type="primary" @click="handleAdd">添加</el-button>
            <el-button type="primary" @click="batchDelete">移除</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="size-form padTop20">
        <el-form @submit.native.prevent label-width="120px">
          <el-form-item label="">
            <el-table
              :data="generateList"
              border
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column
                type="index"
                label="序号"
                header-align="center"
                align="center"
                width="80"
              ></el-table-column>
              <el-table-column
                prop="product_name"
                label="产品"
                header-align="center"
                align="center"
                width="360"
              >
                <template slot-scope="scope">
                  <div class="disCenter itemBox">
                    <div class="imgBox">
                      <img src="~@/assets/img/avatar.png" />
                    </div>
                    <div class="rightBox">
                      <el-tooltip
                        class="item"
                        effect="light"
                        :content="scope.row.product_name"
                        placement="top"
                      >
                        <span class="top overTwoHidden">{{
                          scope.row.product_name
                        }}</span>
                      </el-tooltip>

                      <span class="bottom"
                        >产品编号: {{ scope.row.product_serial }}</span
                      >
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="sku_name"
                label="规格"
                header-align="center"
                align="center"
                width="180"
              ></el-table-column>
              <el-table-column
                label-class-name="thRequired"
                prop="sale_price"
                label="单价（元）"
                header-align="center"
                align="center"
                min-width="130"
              >
                <template slot-scope="scope">
                  <el-input
                    type="number"
                    placeholder="请输入"
                    v-model="scope.row.sale_price"
                    :min="0"
                  >
                  </el-input> </template
              ></el-table-column>
              <el-table-column
                label-class-name="thRequired"
                prop="sale_num"
                label="销售数量"
                header-align="center"
                align="center"
                min-width="130"
              >
                <template slot-scope="scope">
                  <el-input
                    type="number"
                    placeholder="请输入"
                    v-model="scope.row.sale_num"
                    :min="1"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                label-class-name="thRequired"
                prop="total_price"
                label="合计金额（元）"
                header-align="center"
                align="center"
                min-width="150"
              >
                <template slot-scope="scope">
                  {{ (scope.row.sale_price || 0) * (scope.row.sale_num || 0) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="delivery_date"
                label="交付日期"
                header-align="center"
                align="center"
                min-width="150"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.delivery_date"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                prop="remarks"
                label="备注"
                header-align="center"
                align="center"
                width="180"
              >
                <template slot-scope="scope">
                  <el-input placeholder="请输入" v-model="scope.row.remarks">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('handle')"
                fixed="right"
                header-align="center"
                align="center"
                width="120"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-bottom: 36px">
        <div class="disCenter" style="justify-content: flex-end">
          <div style="margin-right: 64px">合计</div>
          <div style="margin-right: 36px">
            总数量： <span class="mainColor storngTip">{{ tipTotal }}</span>
          </div>
          <div>
            订单金额：
            <span class="mainColor storngTip">{{ tipPrice }}</span> 元
          </div>
        </div>
      </div>
      <div style="margin-bottom: 36px">
        <el-button @click="goBack" style="margin-left: 45%; margin-top: 36px"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="dataFormSubmitHandle()"
          style="margin-left: 21px"
          >确定</el-button
        >
      </div>
    </div>
    <el-backtop></el-backtop>
    <el-dialog :visible.sync="dialogVisible" title="查看">
      <img width="100%" :src="dialogImageUrl" class="avatar" />
    </el-dialog>
    <ProductChoose
      v-if="addOrUpdateVisible"
      ref="orderProduct"
      @handleClose="handleClose"
      @handleConfirm="fitConfirm"
      :chooseData="generateList"
    ></ProductChoose>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import ProductChoose from '@/components/product-choose'
import { formatDayTime } from '@/utils'
import { zmGetProvincesArr, zmGetCitiesArr, zmGetAreaArr } from '@/utils/region'
import { getOrderDetail, addOrder, deleteOrderSub } from '@/api'
export default {
  components: {
    ProductChoose,
  },
  data() {
    return {
      visible: false,
      dataForm: {
        id: '',
        name: '',
        order_serial: '',
        sale_date: '',
        customer_name: '',
        phone: '',
        customer_manager: '',
        pay_type: '',
        remarks: '',
        order_serial: '',
        order_serial: '',
        address: '',
      },
      dialogImageUrl: '',
      dialogVisible: false,
      addOrUpdateVisible: false,
      generateList: [],
      productList: [],
      isAdd: true,
      region: '', //三级地址
      province: {}, //省
      city: {}, //市
      area: {}, //县
      provinces: [],
      cities: [],
      areas: [],
      // 批量删除缓存数据
      subChooseInfo: [],
      tipTotal: '',
      tipPrice: '',
    }
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
        sale_date: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'change',
          },
        ],
      }
    },
  },
  activated() {
    this.$refs['dataForm'].resetFields()
    const id = this.$route.params.id
    this.dataForm.sale_date = formatDayTime(new Date().getTime())
    this.dataForm.id = id
    const provinces = zmGetProvincesArr()
    this.provinces = provinces
    this.province = {}
    this.city = {}
    this.area = {}
    this.dataForm.address = ''
    this.cities = []
    this.areas = []
    this.generateList = []
    this.productList = []
    this.subChooseInfo = []
    this.isAdd = true
    this.tipTotal = ''
    this.tipPrice = ''
    if (id) {
      this.fetchDetail(id)
      this.isAdd = false
    }
    // const cityData = zmGetCitiesArr(prov.value);
    // this.cities = cityData;
    // const areaData = zmGetAreaArr(cit.value);
    // this.areas = areaData;
    // this.province = prov;
    // this.city = cit;
    // this.area = country;
  },
  watch: {
    generateList: {
      handler() {
        this.calcTotal()
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    calcTotal() {
      this.tipTotal = this.generateList.reduce((pre, cur) => {
        return pre + Number(cur.sale_num)
      }, 0)
      this.tipPrice = this.generateList.reduce((pre, cur) => {
        return pre + Number(cur?.sale_num || 0) * Number(cur?.sale_price || 0)
      }, 0)
    },
    handleSelectionChange(val) {
      this.subChooseInfo = val
    },
    batchDelete() {
      if (this.subChooseInfo.length < 1) {
        this.$message.warning('请选择您需要移除的数据！')
        return
      }
      let that = this
      let arr = []
      // 删除添加数据
      this.subChooseInfo.forEach((item) => {
        if (that.isAdd || item.id === 0) {
          arr = that.generateList.filter(
            (it) => it.id !== 0 || it.product_sku_id !== item.product_sku_id
          )
          that.generateList = arr
        }
      })

      if (!that.isAdd) {
        // 删除在线数据
        const temp = this.subChooseInfo.filter((item) => item.id !== 0)
        if (temp.length < 1) return
        let info = []
        temp.forEach((item) => info.push(item.id))
        const params = {
          order_id: this.dataForm.id,
          ids: info,
        }
        that
          .$confirm(
            '移除数据中有在线子订单数据，此操作将删除已选择数据, 是否继续?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
          .then(async () => {
            const res = await deleteOrderSub(params)
            if (res?.status === 1) {
              this.$message.success(res?.msg || '')
              let wrapper = []
              info.forEach((item) => {
                wrapper = that.generateList.filter((it) => it.id !== item)
                that.generateList = wrapper
              })
              console.log(that.generateList)
            }
          })
          .catch(() => {})
      }
    },
    cityChange(val) {
      const { value } = val
      const areaData = zmGetAreaArr(value)
      this.areas = areaData
      this.area = {}
    },
    provinceChange(val) {
      const { value } = val
      const cityData = zmGetCitiesArr(value)
      this.cities = cityData
      this.areas = []
      this.city = {}
      this.area = {}
    },
    handleDelete(row) {
      const { product_sku_id, id, order_id } = row
      let arr = []
      if (this.isAdd || id === 0) {
        arr = this.generateList.filter(
          (item) => item.id !== 0 || item.product_sku_id !== product_sku_id
        )
        this.generateList = arr
      } else {
        this.$confirm(
          '此数据为在线子订单数据，此操作将删除该条数据, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(async () => {
            const res = await deleteOrderSub({ order_id, ids: [id] })
            if (res?.status === 1) {
              this.$message.success(res?.msg || '')
              arr = this.generateList.filter((item) => item.id !== id)
              this.generateList = arr
            }
          })
          .catch(() => {})
      }
    },
    fitConfirm(row) {
      console.log(row)
      row.forEach((item) => {
        item.sale_price = row.price
      })
      // row.forEach((item) => {
      //   const { id, material_serial, name, specifications_model } = item
      //   const temp = {
      //     parts_num: 1,
      //     price: null,
      //     day: null,
      //     daily_output: null,
      //     material_id: id,
      //     id: 0,
      //     material_serial,
      //     name,
      //     specifications_model,
      //   }
      //   arr.push(temp)
      // })
      console.log(this.generateList)
      this.generateList = [...this.generateList, ...row]
    },
    handleClose() {
      this.addOrUpdateVisible = false
    },
    handleAdd() {
      this.addOrUpdateVisible = true
    },
    async fetchDetail(id) {
      const params = {
        id,
      }
      const res = await getOrderDetail(params)
      if (res?.status === 1) {
        const data = res?.data || {}
        const {
          order_sub,
          province,
          province_code,
          city,
          city_code,
          district,
          district_code,
          ...info
        } = data
        if (province) {
          const par = {
            value: province_code,
            label: province,
          }
          const cityData = zmGetCitiesArr(province_code)
          this.cities = cityData
          this.province = par
        }
        if (city) {
          const par = {
            value: city_code,
            label: city,
          }
          const areaData = zmGetAreaArr(city_code)
          this.areas = areaData
          this.city = par
        }
        if (district) {
          const par = {
            value: district_code,
            label: district,
          }
          this.area = par
        }
        this.dataForm = info
        // this.dataForm.pid = info.classify_ids;
        // this.dataForm.parentName = info.classify_name;
        this.generateList = order_sub
      }
    },
    goBack() {
      this.$router.go(-1)
    },

    // 表单提交
    dataFormSubmitHandle: debounce(
      function() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (!valid) {
            return false
          }
          // item合计金额不能为空
          let isEmpty = false
          for (let i = 0; i < this.generateList.length; i++) {
            let it = this.generateList[i]
            if (!((it.sale_price || 0) * (it.sale_num || 0))) {
              isEmpty = true
              break
            }
          }
          if (isEmpty) {
            this.$message.warning('单价及销售数量必填，请确认后提交！')
            return
          }
          const params = { ...this.dataForm }
          params.id = this.dataForm.id ? this.dataForm.id : 0
          if (JSON.stringify(this.province) !== '{}') {
            params.province = this.province.label
            params.province_code = this.province.value
          }
          if (JSON.stringify(this.city) !== '{}') {
            params.city = this.city.label
            params.city_code = this.city.value
          }
          if (JSON.stringify(this.area) !== '{}') {
            params.district = this.area.label
            params.district_code = this.area.value
          }
          params.order_sub = this.generateList
          console.log(params)
          const res = await addOrder(params)
          if (res?.status === 1) {
            this.$message.success(res?.msg || '操作成功')
            this.$refs['dataForm'].resetFields()
            this.$router.go(-1)
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
  // watch: {
  //   'dataForm.type' (val) {
  //     this.$refs['dataForm'].clearValidate()
  //   }
  // },
}
</script>

<style lang="scss" scoped>
.add-wrapper {
  background: #fff;
  padding: 20px;
  ::v-deep .el-page-header__title {
    font-size: 12px;
  }

  ::v-deep .el-page-header__content {
    font-size: 12px;
  }
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  .form-wrapper {
    ::v-deep .el-select {
      width: 100%;
    }

    .top-form {
      width: 50%;
      margin-top: 36px;

      .picDes {
        margin-top: 12px;
        font-size: 12px;
        color: #999;
        line-height: 18px;
      }
    }
    .size-form {
      ::v-deep .el-date-editor.el-input,
      .el-date-editor.el-input__inner {
        width: auto;
      }
    }
  }
}
</style>
